package pv.map;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

public class ConvertLatLongURL extends ConvertLatLong {
	private static final String TAG_RESULTS = "results";
	private static final String TAG_GEOMETRY = "geometry";
	private static final String TAG_VIEWPORT = "viewport";
	private static final String TAG_NORTHEAST = "northeast";
	private static final String TAG_LAT = "lat";
	private static final String TAG_LNG = "lng";

	@Override
	public List<LatLng> convert(String address, Context context) {

		if (address == null || address.isEmpty()) {
			return null;
		}
		List<LatLng> result = new ArrayList<LatLng>();
		JSONArray resultsJSON = null;
		JSONParser jParser = new JSONParser();

		address = address.replaceAll(" ", "%20");
		String url = "http://maps.googleapis.com/maps/api/geocode/json?address="
				+ address + "&sensor=true";

		// getting JSON string from URL
		JSONObject json = jParser.getJSONFromUrl(url);

		try {
			// Getting Array of results
			resultsJSON = json.getJSONArray(TAG_RESULTS);

			for (int i = 0; i < resultsJSON.length(); i++) {
				JSONObject r = resultsJSON.getJSONObject(i);

				// geometry and location is again JSON Object
				JSONObject geometry = r.getJSONObject(TAG_GEOMETRY);

				JSONObject viewport = geometry.getJSONObject(TAG_VIEWPORT);

				JSONObject northest = viewport.getJSONObject(TAG_NORTHEAST);

				String lat = northest.getString(TAG_LAT);
				String lng = northest.getString(TAG_LNG);

				result.add(new LatLng(Double.valueOf(lat), Double.valueOf(lng)));
			}

		} catch (JSONException e) {
			return null;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
		return result;
	}

}

class JSONParser {

	InputStream is = null;
	JSONObject jObj = null;
	String json = "";

	// constructor
	public JSONParser() {

	}

	public JSONObject getJSONFromUrl(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}
